package com.hmdp.utils;


import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;

@Slf4j
@Component
public class CacheClient {

    private final StringRedisTemplate stringRedisTemplate;

    //线程池用来给逻辑过期创建新线程使用
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);



    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, Object value, Long time, TimeUnit unit){

        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }


    //设置逻辑过期
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit){


        RedisData redisData = new RedisData();
        redisData.setData(value);

        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));

        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }


    public <R,ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R>type, Function<ID,R> dbFallBack,Long time,TimeUnit unit){
        String key =keyPrefix+id;

        //查询redis缓存
        String Json=stringRedisTemplate.opsForValue().get(key);
        //如果查到了，我还要更新缓存存在时间
        if(StrUtil.isNotBlank(Json)){
            return JSONUtil.toBean(Json,type);
        }
        //上面判断不了空值，这里如果是redis里面有而且是控制，就直接return，就不需要再访问数据库了
        if(Json!=null ) return null;

        //没查到缓存就查数据库，然后加入缓存
        R r = dbFallBack.apply(id);

        //没查到数据库
        if(r==null){
            //为了控制缓存穿透，将空值写入redis，减小数据库压力

            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.SECONDS);

            return null;
        }
        this.set(key,r,time,unit);
        return r;
    }



    //使用逻辑过期来解决缓存击穿
    public <R,ID> R queryWithLogicalExpire(String keyPrefix,ID id,Class<R> type,Function<ID,R> dbFallBack,Long time,TimeUnit unit){
        String key =keyPrefix+id;

        //查询redis缓存
        String Json=stringRedisTemplate.opsForValue().get(key);

        if(StrUtil.isBlank(Json)){

            return null;
        }

        //命中需要先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(Json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //判断是否过期
        if(expireTime.isAfter(LocalDateTime.now())){
            //未过期，直接返回
            return r;
        }
        //已过期，缓存重建
        //获取互斥锁
        String lockKey=LOCK_SHOP_KEY+id;
        boolean isLock = tryLock(lockKey);
        //判断是否获取锁成功
        if(isLock){
            //TODO 成功，开启一个线程并返回
            CACHE_REBUILD_EXECUTOR.submit(()->{
                //重建缓存
                try {
                    //查询数据库
                    R r1 = dbFallBack.apply(id);
                    //写入redis
                    this.setWithLogicalExpire(key,r1,time,unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unlock(lockKey);
                }
            });
        }
        //失败，直接返回
        return r;
    }


    private boolean tryLock(String lock){
        Boolean flag=stringRedisTemplate.opsForValue().setIfAbsent(lock,"1",10,TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String lock){
        stringRedisTemplate.delete(lock);
    }

}
